<template>
  <div class="app-container">
    <!-- 添加或修改租户套餐对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" v-if="open" append-to-body>
      <el-form ref="tenantPackageRef" :model="form" :rules="rules" label-width="110px" :disabled="disabled">
        <el-form-item label="套餐名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名称" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
          <el-tree
              class="tree-border"
              :data="menuOptions"
              show-checkbox
              ref="menu"
              node-key="id"
              :check-strictly="!form.menuCheckStrictly"
              empty-text="加载中，请稍候"
              :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="200" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" v-if="!disabled" @click="submitForm">确 定</el-button>
          <el-button @click="cancel" v-if="!disabled">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dialog">
import { getTenantPackage, addTenantPackage, updateTenantPackage } from "@/api/system/tenant/package";
import {treeselect as menuTreeselect, tenantPackageMenuTreeselect} from "@/api/system/menu";

const { proxy } = getCurrentInstance();

const open = ref(false);
const disabled = ref(false);
const title = ref("");
const single = ref(true);
const menuExpand = ref(true);
const menuNodeAll = ref(true);
const menuOptions = ref([]);

const data = reactive({
  form: {},
  rules: {
  }
});

const emit = defineEmits(["refresh"]);
const { form, rules } = toRefs(data);

/** 打开租户套餐弹框 */
async function show(packageId, _disabled) {
  reset();
  disabled.value = _disabled
  if (packageId) {
    const roleMenu = getTenantPackageMenuTreeselect(packageId);
    await getTenantPackage(packageId).then(response => {
      form.value = response.data;
      proxy.$nextTick(() => {
        roleMenu.then(res => {
          let checkedKeys = res.checkedKeys
          checkedKeys.forEach((v) => {
            proxy.$nextTick(()=>{
              proxy.$refs.menu.setChecked(v, true ,false);
            })
          })
        });
      });
    });
  } else {
    getMenuTreeselect();
  }
  open.value = true
  if (disabled.value) {
    title.value = "详情"
  } else if (packageId) {
    title.value = "修改"
  } else {
    title.value = "新增"
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    packageId: null,
    packageName: null,
    menuIds: null,
    remark: null,
    menuCheckStrictly: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("tenantPackageRef");
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then(response => {
    menuOptions.value = response.data;
  });
}
/** 根据租户套餐ID查询菜单树结构 */
function getTenantPackageMenuTreeselect(roleId) {
  return tenantPackageMenuTreeselect(roleId).then(response => {
    menuOptions.value = response.menus;
    return response;
  });
}
// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = proxy.$refs.menu.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = proxy.$refs.menu.getHalfCheckedKeys();
  checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys ?checkedKeys.join(','): '';
}

// 树权限（展开/折叠）
function handleCheckedTreeExpand(value) {
  let treeList = menuOptions.value;
  for (let i = 0; i < treeList.length; i++) {
    proxy.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
  }
}
// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value) {
  proxy.$refs.menu.setCheckedNodes(value ? menuOptions.value: []);
}
// 树权限（父子联动）
function handleCheckedTreeConnect(value) {
  form.value.menuCheckStrictly = !!value;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tenantPackageRef"].validate(valid => {
    if (valid) {
      form.value.menuIds = getMenuAllCheckedKeys();
      if (form.value.packageId != null) {
        updateTenantPackage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          emit('refresh');
        });
      } else {
        addTenantPackage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          emit('refresh');
        });
      }
    }
  });
}


defineExpose({
  show,
});
</script>
